<template>
  <div class="admin-users">
    <div class="page-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showAddDialog = true">
          添加用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索用户名/邮箱"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchForm.userType"
            placeholder="用户类型"
            clearable
            @change="handleSearch"
          >
            <el-option label="营销人员" value="marketing" />
            <el-option label="客户" value="customer" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="searchForm.userStatus"
            placeholder="用户状态"
            clearable
            @change="handleSearch"
          >
            <el-option label="正常" value="00" />
            <el-option label="禁用" value="01" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 用户列表 -->
    <el-table :data="usersList" style="width: 100%" v-loading="loading">
      <!-- <el-table-column prop="userId" label="用户ID" width="120" /> -->
      <el-table-column prop="userCode" label="登录账号" />
      <!-- <el-table-column prop="nickName" label="昵称" /> -->
      <el-table-column prop="userName" label="使用人" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="phone" label="手机号" />
      <!-- <el-table-column prop="userType" label="用户类型">
        <template #default="scope">
          <el-tag :type="getUserTypeType(scope.row.userType)">
            {{ getUserTypeText(scope.row.userType) }}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column prop="userStatus" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.userStatus === '00' ? 'success' : 'danger'">
            {{ scope.row.userStatus === "00" ? "正常" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <div class="action-buttons">
            <el-button size="small" @click="viewUser(scope.row)">
              查看
            </el-button>
            <el-button size="small" type="primary" @click="editUser(scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteUser(scope.row)"
            >
              删除
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="resetPassword(scope.row)"
            >
              重置密码
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingUser ? '编辑用户' : '添加用户'"
      width="500px"
    >
      <el-form
        :model="userForm"
        :rules="userRules"
        ref="userFormRef"
        label-width="100px"
      >
        <el-form-item label="登录账号" prop="userCode">
          <el-input v-model="userForm.userCode" :disabled="!!editingUser" />
        </el-form-item>
        <!-- <el-form-item label="昵称" prop="nickName">
          <el-input v-model="userForm.nickName" />
        </el-form-item> -->
        <el-form-item label="使用人" prop="userName">
          <el-input v-model="userForm.userName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="密码" prop="userPassword" v-if="!editingUser">
          <el-input
            v-model="userForm.userPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <!-- <el-form-item label="用户类型" prop="userType">
          <el-select v-model="userForm.userType" placeholder="选择用户类型">
            <el-option label="管理员" value="admin" />
            <el-option label="营销人员" value="marketing" />
            <el-option label="客户" value="customer" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="状态" prop="userStatus">
          <el-radio-group v-model="userForm.userStatus">
            <el-radio label="00">正常</el-radio>
            <el-radio label="01">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="性别" prop="gender">
          <el-select v-model="userForm.gender" placeholder="选择性别">
            <el-option label="男" value="male" />
            <el-option label="女" value="female" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="地区" prop="region">
          <el-input v-model="userForm.region" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="userForm.remark" type="textarea" :rows="3" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="saving"
          >保存</el-button
        >
      </template>
    </el-dialog>

    <!-- 查看用户详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="查看用户详情" width="500px">
      <div v-if="viewingUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="登录账号">{{
            viewingUser.userCode || "-"
          }}</el-descriptions-item>
          <!-- <el-descriptions-item label="昵称">{{
            viewingUser.nickName || "-"
          }}</el-descriptions-item> -->
          <el-descriptions-item label="使用人">{{
            viewingUser.userName || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{
            viewingUser.phone || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{
            viewingUser.email || "-"
          }}</el-descriptions-item>
          <!-- <el-descriptions-item label="用户类型">
            <el-tag :type="getUserTypeType(viewingUser.userType)">
              {{ getUserTypeText(viewingUser.userType) }}
            </el-tag>
          </el-descriptions-item> -->
          <el-descriptions-item label="状态">
            <el-tag
              :type="viewingUser.userStatus === '00' ? 'success' : 'danger'"
            >
              {{ viewingUser.userStatus === "00" ? "正常" : "禁用" }}
            </el-tag>
          </el-descriptions-item>
          <!-- <el-descriptions-item label="创建时间">{{
            viewingUser.createTime || "-"
          }}</el-descriptions-item> -->
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { systemApi, userApi } from "@/api/admin";
import request from "@/utils/request";

export default {
  name: "AdminUsers",
  setup() {
    const loading = ref(false);
    const saving = ref(false);
    const showAddDialog = ref(false);
    const editingUser = ref(null);
    const viewDialogVisible = ref(false);
    const viewingUser = ref(null);
    const userFormRef = ref(null);

    // 搜索表单
    const searchForm = reactive({
      keyword: "",
      userType: "",
      userStatus: "",
    });

    // 用户表单
    const userForm = reactive({
      userCode: "",
      nickName: "",
      userName: "",
      email: "",
      phone: "",
      userPassword: "",
      userType: "customer",
      userStatus: "00",
      gender: "",
      nationality: "",
      region: "",
      remark: "",
    });

    // 表单验证规则
    const userRules = {
      userCode: [
        { required: true, message: "请输入登录账号", trigger: "blur" },
        {
          min: 3,
          max: 20,
          message: "登录账号长度在3到20个字符",
          trigger: "blur",
        },
      ],
      // nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
      ],
      phone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        {
          pattern: /^1[3456789]\d{9}$/,
          message: "请输入正确的手机号",
          trigger: "blur",
        },
      ],
      userPassword: [
        { required: true, message: "请输入密码", trigger: "blur" },
        { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
      ],
      // userType: [
      //   { required: true, message: "请选择用户类型", trigger: "change" },
      // ],
    };

    // 分页
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0,
    });

    // 用户数据列表
    const usersList = ref([]);

    // 权限检查
    const hasPermission = (permission) => {
      const userInfo = JSON.parse(localStorage.getItem("adminUser") || "{}");
      if (userInfo.permissions?.includes("all")) return true;
      return userInfo.permissions?.includes(permission) || false;
    };

    // 获取角色类型
    const getUserTypeType = (userType) => {
      const types = {
        admin: "danger",
        marketing: "warning",
        customer: "primary",
      };
      return types[userType] || "info";
    };

    // 获取用户类型文本
    const getUserTypeText = (userType) => {
      const texts = {
        admin: "管理员",
        marketing: "营销人员",
        customer: "客户",
      };
      return texts[userType] || "未知";
    };

    // 搜索
    const handleSearch = () => {
      pagination.current = 1;
      loadUsers();
    };

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        keyword: "",
        role: "",
        status: "",
      });
      handleSearch();
    };

    // 加载用户数据
    const loadUsers = async () => {
      loading.value = true;
      try {
        const params = {
          page: pagination.current,
          size: pagination.size,
        };

        if (searchForm.keyword) params.keyword = searchForm.keyword;
        if (searchForm.userType) params.userType = searchForm.userType;
        if (searchForm.userStatus) params.userStatus = searchForm.userStatus;

        const response = await systemApi.getUserPage(params);
        if (response.code === "200") {
          usersList.value = response.data.records || [];
          pagination.total = response.data.total || 0;
        }
      } catch (error) {
        console.error("加载用户数据失败:", error);
        ElMessage.error("加载用户数据失败");
      } finally {
        loading.value = false;
      }
    };

    // 查看用户
    const viewUser = async (user) => {
      try {
        const res = await request.get(`/api/admin/user/${user.userId}`);
        if (res && (res.code === "200" || res.code === 200)) {
          viewingUser.value = res.data;
          viewDialogVisible.value = true;
        } else {
          ElMessage.error(res?.msg || "获取用户详情失败");
        }
      } catch (e) {
        ElMessage.error("获取用户详情失败");
      }
    };

    // 编辑用户
    const editUser = (user) => {
      editingUser.value = user;
      Object.assign(userForm, {
        userCode: user.userCode || "",
        nickName: user.nickName || "",
        userName: user.userName || "",
        email: user.email || "",
        phone: user.phone || "",
        userPassword: "", // 编辑时不显示密码
        userType: user.userType || "customer",
        userStatus: user.userStatus || "00",
        gender: user.gender || "",
        nationality: user.nationality || "",
        region: user.region || "",
        remark: user.remark || "",
      });
      showAddDialog.value = true;
    };

    // 删除用户
    const deleteUser = async (user) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 "${
            user.nickName || user.userCode
          }" 吗？此操作不可恢复！`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        const response = await systemApi.deleteUser(user.userId);
        if (response.code === "200") {
          ElMessage.success("删除成功");
          loadUsers();
        } else {
          ElMessage.error(response.msg || "删除失败");
        }
      } catch {
        // 用户取消
      }
    };

    // 重置密码
    const resetPassword = async (user) => {
      try {
        await ElMessageBox.confirm(
          `确定要重置用户 "${user.nickName || user.userCode}" 的密码吗？`,
          "确认重置",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        const response = await systemApi.updateUserStatus(
          user.userId,
          "reset_password"
        );
        if (response.code === "200") {
          ElMessage.success("密码重置成功，新密码已发送到用户邮箱");
        } else {
          ElMessage.error(response.msg || "密码重置失败");
        }
      } catch {
        // 用户取消
      }
    };

    // 保存用户
    const saveUser = async () => {
      // 校验表单
      const valid = await userFormRef.value.validate();
      if (!valid) {
        return;
      }
      console.log(123);
      userForm.nickName = userForm.userCode;

      saving.value = true;

      try {
        // 清理数据，移除null、undefined和空字符串值
        const cleanUserData = {};
        Object.keys(userForm).forEach((key) => {
          const value = userForm[key];
          // 编辑用户时，如果密码为空则不传递密码字段
          if (
            editingUser.value &&
            key === "userPassword" &&
            (!value || value.trim() === "")
          ) {
            return; // 跳过空密码字段
          }
          // 只传递有效的非空值
          if (
            value !== null &&
            value !== undefined &&
            value !== "" &&
            value !== "null" &&
            value.toString().trim() !== ""
          ) {
            cleanUserData[key] = value.toString().trim();
          }
        });

        // 确保必填字段有默认值
        if (!cleanUserData.userType) {
          cleanUserData.userType = "customer";
        }
        if (!cleanUserData.userStatus) {
          cleanUserData.userStatus = "00";
        }

        // 确保必填字段存在
        if (!cleanUserData.userCode) {
          ElMessage.error("登录账号不能为空");
          return;
        }
        // if (!cleanUserData.nickName) {
        //   ElMessage.error("昵称不能为空");
        //   return;
        // }
        if (!cleanUserData.email) {
          ElMessage.error("邮箱不能为空");
          return;
        }
        if (!cleanUserData.phone) {
          ElMessage.error("手机号不能为空");
          return;
        }

        // 最终数据验证 - 移除任何可能为null的键
        const finalUserData = {};
        Object.keys(cleanUserData).forEach((key) => {
          if (
            key !== null &&
            key !== undefined &&
            key !== "null" &&
            key.trim() !== ""
          ) {
            finalUserData[key] = cleanUserData[key];
          }
        });

        // 调试日志
        console.log("清理后的用户数据:", finalUserData);

        let response;
        if (editingUser.value) {
          // 编辑用户
          finalUserData.userId = editingUser.value.userId;
          console.log("更新用户数据:", finalUserData);
          response = await systemApi.updateUser(finalUserData);
        } else {
          // 添加用户
          console.log("添加用户数据:", finalUserData);
          response = await systemApi.addUser(finalUserData);
        }

        if (response.code === "200") {
          ElMessage.success(
            editingUser.value ? "用户更新成功" : "用户添加成功"
          );
          showAddDialog.value = false;
          loadUsers();
        } else {
          ElMessage.error(response.msg || "保存失败");
        }

        showAddDialog.value = false;
        editingUser.value = null;
        Object.assign(userForm, {
          userCode: "",
          nickName: "",
          userName: "",
          email: "",
          phone: "",
          userPassword: "",
          userType: "customer",
          userStatus: "00",
          gender: "",
          nationality: "",
          region: "",
          remark: "",
        });
      } catch (error) {
        console.error("保存用户失败:", error);
        ElMessage.error("操作失败");
      } finally {
        saving.value = false;
      }
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size;
      loadUsers();
    };

    const handleCurrentChange = (current) => {
      pagination.current = current;
      loadUsers();
    };

    onMounted(() => {
      loadUsers();
    });

    return {
      loading,
      saving,
      showAddDialog,
      editingUser,
      viewDialogVisible,
      viewingUser,
      searchForm,
      userForm,
      userRules,
      pagination,
      usersList,
      userFormRef,
      hasPermission,
      getUserTypeType,
      getUserTypeText,
      handleSearch,
      resetSearch,
      viewUser,
      editUser,
      deleteUser,
      resetPassword,
      saveUser,
      handleSizeChange,
      handleCurrentChange,
    };
  },
};
</script>

<style scoped>
.admin-users {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  margin: 0;
  flex-shrink: 0;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .action-buttons {
    flex-direction: column;
    gap: 3px;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
